package recommenRatings.presentation;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import recommenRatings.data.JDBCUserDAO;
import recommenRatings.domain.User;
import recommenRatings.utils.MD5Generator;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		if (registrar(request)) {
			HttpSession session = request.getSession(false);
			session.setAttribute("session.user", request
					.getParameter("username"));
			response.sendRedirect("FrontController?res=start.jsp");
		} else {
			response.sendRedirect("error.html");
		}
	}

	private boolean registrar(HttpServletRequest request) {
		Calendar c = Calendar.getInstance();
		c.set(Integer.valueOf(request.getParameter("year")), Integer
				.valueOf(request.getParameter("month")), Integer
				.valueOf(request.getParameter("day")));
		boolean gender = false;
		if (request.getParameter("gender").equals("Male"))
			gender = true;

		User u = new User(request.getParameter("name"), request
				.getParameter("surname"), request.getParameter("address"),
				request.getParameter("telephone"), request
						.getParameter("mobilePhone"), c.getTime(), request
						.getParameter("email"), request
						.getParameter("username"), MD5Generator.md5(request
						.getParameter("pass")), gender, request
						.getParameter("city"), request.getParameter("state"));
		return new JDBCUserDAO().insert(u);
	}
}
